package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.ShoppingCarMapper;
import com.itheima.pojo.Cart;
import com.itheima.pojo.Result;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCarMapper, Cart> implements ShoppingCartService {

    @Autowired
    private ShoppingCarMapper mapper;

    /**
     * 查询用户并添加商品
     *
     * @param cart
     * @return
     */
    @Override
    public Result add(Cart cart) {
        //1.根据id查询出用户所有的商品
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, cart.getUserId());
        List<Cart> carts = mapper.selectList(wrapper);
        //补全数据
        cart.setNumber(null);//默认添加一次，数量为1
        cart.setCreateTime(new Date());
        //2.判断集合看看存不存在该id的对象
        if (carts.size() == 0) {//根据id查询,集合为空,不存在,直接添加
            mapper.insert(cart);
            return new Result(1, "添加成功!");
        }
        //3.如果存在该id 的用户,遍历得到该对象,判断是否存在相同商品
        for (Cart cart1 : carts) {
            //如果菜品id一致数量加一,金额加一
            if (cart1.getDishId() == cart.getDishId()) {
                cart1.setNumber(cart1.getNumber() + 1);
                cart1.setAmount(cart1.getAmount() + cart.getAmount());
                //3.1更新数据,把新修改的对象数据传进去,调用mapper修改
                mapper.updateById(cart1);
                return new Result(1,"添加成功!");
            }
        }
        //4.如果没有找到则直接添加对应数据就好了
        mapper.insert(cart);
        return new Result(1,"添加成功!");
    }

    /**
     * 根据id查询购物车里面的数据
     *
     * @param id
     * @return
     */
    @Override
    public Result findById(Long id) {
        //lambd条件对象:判断id是否与用户id一致
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,id);
        List<Cart> list = mapper.selectList(wrapper);
        //判断是否查到数据,当查询集合长度为0
        if (list.size()==0){
            return new Result(0,"查无数据!");
        }
        return new Result(1,"查询成功!",list);
    }

    @Override
    public Result clean(Long id) {
        LambdaQueryWrapper<Cart> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Cart::getUserId,id);
        int i = mapper.delete(wapper);
        if (i<=0){
            return new Result(0,"没有购物车数据!");
        }
        return new Result(1,"购物车已经清空!");
    }
}
